package hash;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description: 1.两数之和
 * User: Li_yizYa
 * Date: 2025—03—26
 * Time: 22:28
 */
public class Solution4 {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int[] ret = twoSum(nums, 9);
        for (int i : ret) {
            System.out.print(i + " ");
        }
        System.out.println();
    }

    /**
     * HashMap写法
     * @param nums
     * @param target
     * @return
     */
    private static int[] twoSum(int[] nums, int target) {
        int[] ret = new int[2];
        if (nums == null || nums.length == 0) {
            return ret;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int tmp = target - nums[i];
            if (map.containsKey(tmp)) {
                ret[0] = map.get(tmp);
                ret[1] = i;
            }
            map.put(nums[i], i);
        }
        return ret;
    }
    /**
     * 暴力解法
     * @param nums
     * @param target
     * @return
     */
    private static int[] twoSum1(int[] nums, int target) {
        int[] ret = new int[2];
        if (nums == null || nums.length == 0) {
            return ret;
        }
        for (int i = 0; i < nums.length; i++) {
            int tmp = target - nums[i];
            for (int j = i +1; j < nums.length; j++) {
                if (tmp == nums[j]) {
                    ret[0] = i;
                    ret[1] = j;
                }
            }
        }
        return ret;
    }
}
